//
//  ConNearAcInfoViewController.m
//  Shengzhuli
//
//  Created by FXGuo on 2017/8/9.
//  Copyright © 2017年 kamangkeji. All rights reserved.
//

#import "ConNearAcInfoViewController.h"
#import "NearAcInfoCell.h"
#import "AcNewFlowViewCell.h"
#import "CustomerCell.h"
#import "ClubNetwork.h"
#import "SZLAccountHelper.h"
#import "MBProgressHUD+MJ.h"
#import "SingleNetService.h"
#import "ConReportAlreadyController.h"
#import "ConReportViewController.h"
#import "ChatViewController.h"
#import "SZLTabBarViewController.h"
#import "PersonNetWork.h"
#import "ShareTool.h"
#import "ConClubShowViewController.h"
#import "ConPublicNearViewController.h"
#import "NSDate+Category.h"
#import "ShowShareView.h"
#import "ConNewClubDetailVc.h"

@interface ConNearAcInfoViewController ()<UITableViewDataSource,UITableViewDelegate>

@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) ActivityDetailModel *detailModel;
@property (nonatomic,strong) PersonInfo *info;
@property (nonatomic,weak) UIButton *shareBtn;

@end

@implementation ConNearAcInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"近期活动";
    [self.view addSubview:self.tableView];
    [self setNavi];
    [self configNaviColor];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self getNearAcNewDetail];
    });
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(loginClicked) name:UserLogined object:nil];
}
- (void)loginClicked
{
    [self getNearAcNewDetail];
}
- (void)setNavi
{
    UIButton *shareBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 25,25)];
    shareBtn.titleLabel.font = Font(15);
    [shareBtn setTitleColor:RGBColor(255, 121, 201) forState:UIControlStateNormal];
    [shareBtn addTarget:self action:@selector(shareClick:) forControlEvents:UIControlEventTouchUpInside];
    self.shareBtn = shareBtn;
    
    UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    negativeSpacer.width = -10;
    self.navigationItem.rightBarButtonItems = @[negativeSpacer,[[UIBarButtonItem alloc]initWithCustomView:shareBtn]];
}
- (void)shareClick:(UIButton *)btn
{
    if (btn.tag == 1) {//分享
        if ([SZLAccountHelper shouldLogin]) return;
        ShareContentModel *model = [[ShareContentModel alloc]init];
        model.title = self.detailModel.title;
        model.pageUrl = self.detailModel.webActivityUrl;
        model.content = self.detailModel.flow;
        model.sharePicUrl = [self.detailModel.activityPictureUrl componentsSeparatedByString:@"#"].firstObject;
        model.idd = [NSString stringWithFormat:@"%ld",(long)self.ID];
        [ShareTool share:model];
        
    }else {//编辑
//        ConPublicNearViewController *nearVc = [[ConPublicNearViewController alloc]init];
//        nearVc.nearModel = self.detailModel;
//        nearVc.publicNearBlock = ^{
//            [self getNearAcNewDetail];
//        };
//        [self.navigationController pushViewController:nearVc animated:YES];
    }
}
- (void)configNaviColor
{
    CGSize imageSize = CGSizeMake(320,64);
    UIGraphicsBeginImageContextWithOptions(imageSize,0, [UIScreen mainScreen].scale);
    [[UIColor whiteColor] set];
    UIRectFill(CGRectMake(0,0, imageSize.width, imageSize.height));
    UIImage *pressedColorImg = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    [self.navigationController.navigationBar setBackgroundImage:pressedColorImg forBarMetrics:UIBarMetricsDefault];
    
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
    
    self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:[UIColor blackColor],NSFontAttributeName:[UIFont systemFontOfSize:20]};
    
}

- (UIBarButtonItem *)customBackItemWithTarget:(id)target
                                       action:(SEL)action
{
    UIButton *backBtn = [[UIButton alloc]init];
    backBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [backBtn setBackgroundImage:[UIImage imageNamed:@"ic_left_back"] forState:UIControlStateNormal];
    [backBtn setBackgroundImage:[UIImage imageNamed:@"ic_left_back_select"] forState:UIControlStateHighlighted];
    [backBtn addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
    [backBtn sizeToFit];
    backBtn.contentEdgeInsets = UIEdgeInsetsMake(0, -20, 0, 0);
    return [[UIBarButtonItem alloc]initWithCustomView:backBtn];
}

#pragma mark - Table view data delegate
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0 ||section == 2) {
        return 0.01;
    }
    return 10;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    return nil;
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section != 2) {
        return 1;
    }
    return self.detailModel.guestList.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 560;
    }else if (indexPath.section == 1) {
        AcNewFlowViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([AcNewFlowViewCell class])];
        return [cell calculateCellH:self.detailModel];
    }
    return 90;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        NearAcInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([NearAcInfoCell class])];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.model = self.detailModel;
        cell.focusClick = ^(UIButton *btn, NSInteger type) {
            [self addFocus:btn type:type];
        };
        cell.clubClick = ^{
            ConNewClubDetailVc *detailVc = [[ConNewClubDetailVc alloc]init];
            detailVc.ID = self.detailModel.clubId;
            [self.navigationController pushViewController:detailVc animated:YES];
        };
        return cell;
    }else if (indexPath.section == 1) {
        AcNewFlowViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([AcNewFlowViewCell class])];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.model = self.detailModel;
        return cell;
    }
    CustomerCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([CustomerCell class])];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.model = self.detailModel.guestList[indexPath.row];
    return cell;
}

- (IBAction)toolBarClick:(UIButton *)btn
{
    if (btn.tag == 0||btn.tag == 2) {
        if ([SZLAccountHelper shouldLogin]) return;
    }
    if (btn.tag == 0) {
        if (!self.info) {
            [self getPersonInfo];
        }else {
            [self jumpToChat];
        }
    }else if (btn.tag == 1) {
        ConReportAlreadyController *reVc = [[ConReportAlreadyController alloc]init];
        reVc.ID = self.detailModel.ID;
        [self.navigationController pushViewController:reVc animated:YES];
    }else {
//        if ([[SZLAccountHelper shareInstance].mobilePhone isEqualToString:self.detailModel.mobilePhone]) {
//            [MBProgressHUD showError:@"不能报名自己的活动" toView:self.view];
//            return;
//        }
        NSDateFormatter *formater = [[NSDateFormatter alloc]init];
        formater.dateFormat = @"yyyy-MM-dd HH:mm";
        NSDate *holdDate = [formater dateFromString:self.detailModel.holdDate];
        BOOL isPast = [holdDate isInPast];
        if (isPast) {
            [MBProgressHUD showError:@"活动已举办完成" toView:self.view];
            return;
        }
        [self reportClick];
    }
}
//活动报名
- (void)reportClick
{
    NSMutableDictionary *parame = [NSMutableDictionary dictionary];
    parame[@"token"] = [SZLAccountHelper shareInstance].token;
    parame[@"activityId"] = @(self.detailModel.ID);
    parame[@"registrationName"] = [SZLAccountHelper shareInstance].name;
    parame[@"registrationPhone"] = [SZLAccountHelper shareInstance].mobilePhone;
    [self showClearBgWaiter];
    [ClubNetwork nearActivityReportWithParame:parame response:^(BOOL success, NSString *msg) {
        [self hideWaiter];
        if (success) {
            [MBProgressHUD showSuccess:@"报名成功"];
        }else {
            [MBProgressHUD showError:msg];
        }
    }];
}
- (void)jumpToChat
{
    if ([[SZLAccountHelper shareInstance].mobilePhone isEqualToString:self.detailModel.mobilePhone]) {
        [MBProgressHUD showError:@"不能跟自己聊天"];
        return;
    }
    ChatViewController *chatController = [[ChatViewController alloc]initWithConversationChatter:self.detailModel.mobilePhone conversationType:EMConversationTypeChat];
    chatController.isFromeNear = YES;
    chatController.title = self.detailModel.clubName;
    chatController.info = self.info;
    EaseUserModel *model = [[EaseUserModel alloc]initWithBuddy:self.detailModel.mobilePhone];
    model.nickname = self.info.nickName;
    model.avatarURLPath = self.info.portraitUrl;
    //            model.ID = self.ID;
    chatController.model = model;
    [self.navigationController pushViewController:chatController animated:YES];
}
- (void)getPersonInfo
{
    NSMutableDictionary *parame = [NSMutableDictionary dictionary];
    parame[@"token"] = [SZLAccountHelper shareInstance].token;
    [self showClearBgWaiter];
    [PersonNetWork getPersonInfoWithParame:parame response:^(BOOL success, NSString *msg,NSString *errorCode,PersonInfo *info) {
        [self hideWaiter];
        [self hideReloadView];
        if (success) {
            self.info = info;
            [self jumpToChat];
        }else{
            [MBProgressHUD showError:msg toView:self.view];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                if ([errorCode isEqualToString:NoLoginStatus]) {
                    [self.navigationController popToRootViewControllerAnimated:YES];
                    SZLTabBarViewController *barVc = (SZLTabBarViewController*)[UIApplication sharedApplication].keyWindow.rootViewController;
                    barVc.selectedIndex = 0;
                    [SZLAccountHelper clearAlreadyInfo];
                    [SZLAccountHelper shouldLogin];
                }
            });
        }
    }];
}

- (void)getNearAcNewDetail
{
    NSMutableDictionary *parame = [NSMutableDictionary dictionary];
    if ([SZLAccountHelper isAlreadyLogin]) {
        parame[@"token"] = [SZLAccountHelper shareInstance].token;
    }
    parame[@"id"] = @(self.ID);
    [self showClearBgWaiter];
    [ClubNetwork getNearAcNewDetailWithParame:parame response:^(BOOL success, NSString *msg,ActivityDetailModel *model) {
        [self hideWaiter];
        if (success) {
            self.detailModel = model;
            self.title = model.title;
            if (model.activityType == 1) {
                [self.shareBtn setImage:GetImage(@"活动分享") forState:UIControlStateNormal];
                self.shareBtn.tag = 1;
            }else {
//                [self.shareBtn setTitle:@"编辑" forState:UIControlStateNormal];
//                self.shareBtn.width = 50;
//                self.shareBtn.tag = 0;
            }
            [self.tableView reloadData];
        }else {
            [MBProgressHUD showError:msg];
        }
    }];
}
- (void)addFocus:(UIButton *)btn type:(NSInteger)type
{
    NSMutableDictionary *parame = [NSMutableDictionary dictionary];
    parame[@"token"] = [SZLAccountHelper shareInstance].token;
    parame[@"clubId"] = @(self.detailModel.clubId);
    [SingleNetService addFocusParame:parame response:^(BOOL success, NSString *msg) {
        if (success) {
            self.detailModel.keepStatus = !self.detailModel.keepStatus;
            if (self.detailModel.keepStatus == 1) {
                [self showOnlyText:@"关注成功"];
                [btn setTitle:@"已关注" forState:UIControlStateNormal];
            }else {
                [self showOnlyText:@"取消关注成功"];
                [btn setTitle:@"+关注" forState:UIControlStateNormal];
            }
        }else {
            [MBProgressHUD showError:msg];
            if ([msg isEqualToString:NoLoginError]) {
//                [self.navigationController popToRootViewControllerAnimated:YES];
//                SZLTabBarViewController *barVc = (SZLTabBarViewController*)[UIApplication sharedApplication].keyWindow.rootViewController;
//                barVc.selectedIndex = 0;
                [SZLAccountHelper clearAlreadyInfo];
                [SZLAccountHelper shouldLogin];
            }
        }
    }];
}


- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, ScreenW,ScreenH-SafeAreaTopHeight-50) style:UITableViewStyleGrouped];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.sectionFooterHeight = 0.01;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.backgroundColor = RGBColor(239, 239, 244);
        _tableView.contentInset = UIEdgeInsetsMake(0, 0, 49, 0);
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.tableFooterView = [[UIView alloc]init];
        [_tableView registerNib:[UINib nibWithNibName:NSStringFromClass([NearAcInfoCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([NearAcInfoCell class])];
        [_tableView registerNib:[UINib nibWithNibName:NSStringFromClass([AcNewFlowViewCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([AcNewFlowViewCell class])];
        [_tableView registerNib:[UINib nibWithNibName:NSStringFromClass([CustomerCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([CustomerCell class])];
    }
    return _tableView;
}

@end
